package com.liubujun.nio;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Author: liubujun
 * @Date: 2022/2/12 19:41
 */


public class FileChannelDemo2 {

    public static void main(String[] args) throws Exception {
        //创建FileChannel
        RandomAccessFile accessFile = new RandomAccessFile("C:\\Users\\LiuBuJun\\Desktop\\liubujun\\00.txt","rw");
        FileChannel channel = accessFile.getChannel();

        //创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //准备要写入的数据
        String str = "hello world";
        buffer.clear();
        //写入内容
        buffer.put(str.getBytes());
        buffer.flip();
        //因不清楚能一次性写入多少数据，所以需要放在循序里面
        while (buffer.hasRemaining()) {
            channel.write(buffer);
        }
        //关闭
        channel.close();
        System.out.println("写入完成");
    }
}
